package com.tech.platform.cms.databases.mybatis.sqlParser;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.core.parser.SqlInfo;
import com.baomidou.mybatisplus.core.toolkit.TableNameParser;
import com.tech.platform.cms.databases.mybatis.sqlParser.handler.AbstractDynamicTableHandler;
import lombok.Setter;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Collection;

/**
 * @author shengqiang.wu
 * @date 2019/12/30/030 18:27
 * @desc 使用mybatis-plus 的 TableNameParser 直接提取表名,便于理解
 */
@Setter
public class DynamicTableParser implements ISqlParser{

    private AbstractDynamicTableHandler tableHandler;

    @Override
    public SqlInfo parser(MetaObject metaObject, String sql) {
        if(doFilter(metaObject,sql)){
            Collection<String> tables = new TableNameParser(sql).tables();
            String parsedSql = sql;
            boolean sqlParsed = false;
            if(CollUtil.isNotEmpty(tables)){
                for (String tableName : tables){
                    parsedSql = tableHandler.process(metaObject,parsedSql,tableName);
                    sqlParsed = true;
                }
            }

            if(sqlParsed){
                return new SqlInfo().setSql(parsedSql);
            }
        }
        return null;
    }
}
